package cn.itcast.controller;


import cn.itcast.constant.MessageConstant;

import cn.itcast.entity.OrderSettingVo;
import cn.itcast.entity.Result;


import cn.itcast.pojo.OrderSetting;
import cn.itcast.pojo.Params;
import cn.itcast.service.OrderSettingService;
import cn.itcast.utils.POIUtils;
import com.alibaba.dubbo.config.annotation.Reference;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Reference
    private OrderSettingService orderSettingService;

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 根据日期查询预约
     */
    @GetMapping("getOrderSettingsByMonth")
    public Result getOrderSettingsByMonth(@RequestParam("date") String date){

        try {

            List<OrderSettingVo> order = orderSettingService.findOrderByMonth(date);

            //转为json
            String orderjson = objectMapper.writeValueAsString(order);

            //System.out.println(orderjson);

            return new Result(true, MessageConstant.GET_ORDERSETTING_SUCCESS,order);
        } catch (Exception e) {
            System.out.println(e);
            return new Result(false, MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    /**
     * 设置可预约人数
     */
    @PutMapping("updateOrderSettingNumber")
    public Result updateOrderSettingNumber(@RequestBody Params param){

        try {


            orderSettingService.OrderSettingNumber(param);
            return new Result(true,MessageConstant.ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ORDERSETTING_FAIL);
        }
    }


    /**
     * 上传批量添加
     * @param excelFile
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) {
        try {
            List<String[]> list = POIUtils.readExcel(excelFile);

            List<Params> ParamsList = new ArrayList<>();

            //将数据添加到orderSetting中
            for (String[] strings : list) {

                Params Params = new Params(strings[0], Integer.parseInt(strings[1]));

                ParamsList.add(Params);
            }

            orderSettingService.save(ParamsList);
            return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }
}
